import { createStore } from 'vuex'

const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

const getLocalCartList = () => {
  // { shopId: {shopName:'', productList:{ productId: {} }}}
  try {
    return JSON.parse(localStorage.cartList) || {}
  } catch (error) {
    return {}
  }
}

export default createStore({
  state: {
    cartList: getLocalCartList()
  },
  mutations: {
    // 加减购物车商品数量
    changeCartItemInfo (state, payload) {
      const { shopId, productId, productInfo, num } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      let product = shopInfo.productList[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo
      }
      product.count += num
      if (num > 0) { product.check = true }
      if (product.count < 0) { product.count = 0 }
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },

    changeCartItemChecked (state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      // console.log(product)
      product.check = !product.check
      setLocalCartList(state)
    },

    cleanCartProducts (state, paload) {
      const { shopId } = paload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },

    setCartItemsChecked (state, paload) {
      const { shopId } = paload
      const products = state.cartList[shopId].productList
      for (const i in products) {
        products[i].check = true
      }
      setLocalCartList(state)
    },

    changeShopName (state, paload) {
      const { shopId, shopName } = paload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },

    // 清空购物车
    clearCartData (state, shopId) {
      state.cartList[shopId].productList = {}
    }
  },
  actions: {
  },
  modules: {
  }
})
